package com.java.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.bind.annotation.RequestBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.mapper.GradeMapper;
import com.java.po.Grade;
import com.java.po.GradeMap;
import com.java.service.GradeService;
import com.java.tool.AjaxJson;

/**
 * Title:GradeServiceImpl.java
 * Description:
 * @author:sprogrammer
 * @time:2018年3月13日下午3:38:36
 */
public class GradeServiceImpl implements GradeService {

	@Autowired
	private GradeMapper gradeMapper;
	private AjaxJson ajaxJson;
	
	public GradeServiceImpl(){
		@SuppressWarnings("resource")
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
		gradeMapper = (GradeMapper) applicationContext.getBean("gradeMapper");		
		ajaxJson = new AjaxJson();
	}
	
	public void cleanAjaxJson(){
		ajaxJson.setData("");
		ajaxJson.setTotal(0);
		ajaxJson.setMessage("");
	}
	
	@Override
	public AjaxJson insertGrade(Grade grade) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		int flag = gradeMapper.insertGrade(grade);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson deleteGrade(Grade grade) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		int flag = gradeMapper.deleteGrade(grade);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson updateGrade(Grade grade) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		int flag = gradeMapper.updateGrade(grade);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson findAllGeade(GradeMap gradeMap) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		Grade grade =new Grade();
		int page = gradeMap.getPage();
		int pageSize = gradeMap.getPageSize();
		if(gradeMap.getGrade()!=null){
			grade = gradeMap.getGrade();
		}
		PageHelper.startPage(page,pageSize);
		List<Grade> list = gradeMapper.findAllGeade(grade);
		PageInfo<Grade> pageInfo = new PageInfo<>(list);
		ajaxJson.setData(pageInfo.getList());
		ajaxJson.setTotal((int)pageInfo.getTotal());
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson findGradeByid(@RequestBody Grade grade) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		grade = gradeMapper.findGradeByid(grade);
		ajaxJson.setData(grade);
		ajaxJson.setMessage("success");
		ajaxJson.setTotal(1);
		return ajaxJson;
	}

}
